//
//  JCCBindPhoneViewController.swift
//  剂查查
//
//  Created by xianquan on 2024/12/11.
//  Copyright © 2024 shipin. All rights reserved.
//

import CommonTools
import TYUIKit

class JCCBindPhoneViewController: BaseViewController {
    
    var token: String = ""
    
    var phoneNo: String = ""
    
    var authCode: String = ""
    
    var authView: AuthCodeView?

    override func viewDidLoad() {
        super.viewDidLoad()
        setTitle("")

        setupUI()
    }
    
    
    func setupUI() {
        let iv = UIImageView(image: UIImage(named: "bind_phone_logo"), in: view) { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(70 + TY_NaviBarHeight())
            make.width.equalTo(64)
            make.height.equalTo(69)
        }
        
        let tips = UILabel(font: 19.regular, textColor: .black3, in: view){ make in
            make.centerX.equalToSuperview()
            make.top.equalTo(iv.snp.bottom).offset(45)
        }
        tips.text = "验证手机号"
        
        let phoneView = PhoneView {[weak self] text in
            self?.phoneNo = text
            self?.authView?.updatePhoneNo(text)
        }
        view.addSubview(phoneView)
        phoneView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(tips.snp.bottom).offset(34)
            make.height.equalTo(35)
        }
        
        let authView = AuthCodeView {[weak self] text in
            self?.authCode = text
        }
        self.authView = authView
        view.addSubview(authView)
        authView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(phoneView.snp.bottom)
            make.height.equalTo(56)
        }
        
        let btn = UIButton(image: nil, title: "进入首页", titleColor: .white, font: 18.regular, in: view) { make in
            make.leading.equalTo(62.5)
            make.trailing.equalTo(-62.5)
            make.top.equalTo(authView.snp.bottom).offset(32)
            make.height.equalTo(40)
        }
        btn.setBackgroundColor(.selectedColor, for: .normal)
        btn.cut(withRadius: 20)
        btn.addBlock(for: .touchUpInside) {[unowned self] _ in
            if !phoneNo.validate(.phoneNum)  {
                toast(message: "请输入正确手机号")
                return
            }
            if !authCode.validate(.authCode) {
                toast(message: "请输入正确验证码")
                return
            }
            if token.count == 0 {
                toast(message: "token有误")
                return
            }
            NetworkRequest.request(networkType: .bindPhone(phone: phoneNo, verify: authCode, token: token)) {[weak self] result in
                guard let self = self else {return}
                switch result {
                case .success(let response):
                    XWLog(value: "绑定成功")
                    UserDefaults.standard.set(token, forKey: "token")
                    pushToSBVC(name: "JCCScanTipViewController")
                    JCCUser.loadUserInfo()
                case .failure(let error):
                    XWLog(value: "绑定失败：\(error)")
                }
            }
        }
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}


extension JCCBindPhoneViewController {
    class PhoneView: UIView {
        init(callback: @escaping (_ text: String) -> ()) {
            super.init(frame: .zero)
            
            let iv = UIImageView(image: UIImage(named: "bind_phone"), in: self) { make in
                make.leading.equalTo(42)
                make.top.equalTo(0)
                make.width.height.equalTo(20)
            }
            iv.cut(withRadius: 0, borderWidth: 1, color: .white)
            
            let label = UILabel(font: 14.regular, textColor: .black2, in: self) { make in
                make.leading.equalTo(iv.snp.trailing).offset(5)
                make.top.equalTo(5)
                make.width.equalTo(30)
            }
            label.text = "+86"
            
            let tf = UITextField(font: 14.regular, textColor: .black3, text: "", placeholder: "请输入手机号码", pattern: .num, maxLength: 11, in: self) { make in
                make.leading.equalTo(label.snp.trailing).offset(10)
                make.centerY.equalTo(iv)
                make.trailing.equalTo(-42)
            } _: { text in
                callback(text)
            }
            tf.keyboardType = .numberPad
            
            UIView(backgroundColor: .blacke, in: self) { make in
                make.leading.equalTo(37)
                make.trailing.equalTo(-37)
                make.bottom.equalToSuperview()
                make.height.equalTo(1)
            }

        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}


extension JCCBindPhoneViewController {
    class AuthCodeView: UIView {
        
        var downBtn: CountdownButton?
        
        var phoneNo: String = ""
        
        init(callback: @escaping (_ text: String) -> ()) {
            super.init(frame: .zero)
            
            let downBtn = CountdownButton(image: nil, title: "获取验证码", titleColor: .selectedColor, font: UIFont.systemFont(ofSize: 18, weight: .medium), in: self) { make in
                make.top.equalToSuperview()
                make.height.equalToSuperview()
                make.trailing.equalTo(-37)
                make.width.equalTo(95)
            }
            self.downBtn = downBtn
            downBtn.setTitleColor(.selectedColorApl(0.4), for: .disabled)
            downBtn.isEnabled = false
            downBtn.usage = .password
            downBtn.complete = { [weak self] in
                if self?.phoneNo.count == 11 {
                    self?.downBtn?.isEnabled = true
                }
            }
            
            
            let codeTf = UITextField(font: 14.regular, textColor: .black3, text: "", placeholder: "请输入手机号码", pattern: .num, maxLength: 6, in: self) { make in
                make.leading.equalTo(37)
                make.centerY.equalTo(downBtn)
                make.trailing.equalTo(downBtn.snp.leading)
            } _: { text in
                callback(text)
            }
            codeTf.keyboardType = .numberPad
            
            downBtn.addBlock(for: .touchUpInside) {[weak self] sender in
                
                let phoneNum = self?.phoneNo ?? ""
                if !phoneNum.validate(.phoneNum) {
                    toast(message: "请填写正确的手机号！")
                    return
                }
                codeTf.becomeFirstResponder()
                NetworkRequest.request(networkType: .getAuthCode(phone: self?.phoneNo ?? "")) { result in
                    switch result {
                    case .success:
                        XWLog(value: "获取验证码成功")
                        guard let sender = sender as? CountdownButton else {return}
                        sender.beginCountdown()
                        sender.isEnabled = false
                    case .failure(let error):
                        XWLog(value: "获取验证码失败:\(error)")
                    }
                }
                
            }
            
            UIView(backgroundColor: .blacke, in: self) { make in
                make.leading.equalTo(37)
                make.trailing.equalTo(-37)
                make.bottom.equalToSuperview()
                make.height.equalTo(1)
            }

        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        func updatePhoneNo(_ phoneNo: String) {
            self.phoneNo = phoneNo
            guard let downBtn = self.downBtn else {return}
            if (!downBtn.isCountdowning) {
                downBtn.isEnabled = phoneNo.count == 11
            }
        }
    }
}
